package ahxu.search.db;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.sql.DataSource;

import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

public class DefaultFinalResultDao implements IFinalResultDao {
	private DataSource dataSource;
	public static final String table="FINAL_RESULT";
	public DefaultFinalResultDao(DataSource dataSource){
		this.dataSource=dataSource;
	}
	
	/* (non-Javadoc)
	 * @see ahxu.search.db.IFinalResultDao#findResults(java.lang.String, java.lang.String, java.lang.String, int, int)
	 */
	public PageResults<FinalResult> findResults(String name,String address,String phone,int pageNo,int pageSize) throws FinalResultDaoException{
		try{
			PageResults<FinalResult> ret=new PageResults<FinalResult>();
			ret.setPageSize(pageSize);
			ret.setCurrentPage(pageNo);
				String sql="select * from " +table+ " where 1=1 ";
				String totalSql= "select count(*) from " +table+ " where 1=1 ";
				String querySql="";
				Map queryValue=new HashMap();
				if(!StringUtils.isEmpty(name)){
					querySql+=" and name like :name ";
					queryValue.put("name", "%"+name+"%");
				}
				if(!StringUtils.isEmpty(address)){
					querySql+=" and address like :address ";
					queryValue.put("address", "%"+address+"%");
				}
				if(!StringUtils.isEmpty(phone)){
					querySql+=" and phone like :phone ";
					queryValue.put("phone", "%"+phone+"%");
				}
				//querySql+=" limit "
				SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
				
			    int total=simpleJdbcTemplate.queryForInt(totalSql+querySql, queryValue);
			    
			    ret.setTotalCount(total);
			    
			    querySql+=" limit " +ret.getPageSize()+" offset "+(ret.getResultsFrom()-1);
			    
			    ParameterizedRowMapper<FinalResult> mapper = new ParameterizedRowMapper<FinalResult>() {
				    
			        // notice the return type with respect to Java 5 covariant return types
			        public FinalResult mapRow(ResultSet rs, int rowNum) throws SQLException {
			        	FinalResult obj = new FinalResult();
			        	obj.setId(rs.getString("id"));
			        	obj.setName(rs.getString("name"));
			        	obj.setAddress(rs.getString("address"));
			        	obj.setPhone(rs.getString("phone"));
			            
			            return obj;
			        }
			    };
				List<FinalResult> retResults=simpleJdbcTemplate.query(sql+querySql, mapper, queryValue);
				ret.setResults(retResults);

			
			return ret;
		}catch(Exception e){
			throw new FinalResultDaoException(e);
		}
	}

	public String save(String name, String address, String phone) throws FinalResultDaoException {
		String insertSQL="insert into " +table+
		"(ID,NAME,ADDRESS,PHONE)" +
		"values" +
		"(?,?,?,?)";
		SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
		String id=UUID.randomUUID().toString();
		simpleJdbcTemplate.update(insertSQL,
				id,
				name,
				address,
				phone);
		return id;
	}

	public String save(FinalResult finalResult) throws FinalResultDaoException {
		String insertSQL="insert into " +table+
		"(ID,NAME,ADDRESS,PHONE,CRAWLID)" +
		"values" +
		"(?,?,?,?,?)";
		SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
		String id=UUID.randomUUID().toString();
		simpleJdbcTemplate.update(insertSQL,
				id,
				finalResult.getName(),
				finalResult.getAddress(),
				finalResult.getPhone(),
				finalResult.getCrawlId());
		return id;
	}
}
